package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: Rodgers
 * @Date 2022/3/17 10:29
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;

    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //1.接收请求数据封装到ShoppingCart对象中
        //2.获取登录数据用户的id封装到ShoppingCart对象中
        Long id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);

        //3.调用业务进行添加购物车操作
        ShoppingCart shoppingCartNew = shoppingCartService.addCart(shoppingCart);

        return R.success(shoppingCartNew);
    }

    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAllByUserId(HttpSession session){
        //1.获取登录用户id
        Long userId = (Long) session.getAttribute("user");

        //2.调用业务获取用户的购物车集合数据
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAllByUserId(userId);

        return R.success(shoppingCartList);
    }

    public R<String> clean(HttpSession session){
        //获取用户id
        Long userId = (Long) session.getAttribute("user");

        //调用业务清空购物车
        shoppingCartService.clean(userId);

        return R.success("清空购物车成功");
    }
}
